if


if

The sentence if is used to execute a computer instructions (or group of computer instructions) only when some conditions are met. Without the sentence if all instructions in the program would have to be executed. Thus, the sentence if increases the flexibility of program by executing a group of instructions only under some conditions.
La instrucción if es usada para ejecutar una instrucción de computadora (o un grupo de instrucciones) solamente cuando algunas condiciones se cumplen. Si la instrucción if no existiera todas las órdenes o líneas de código se ejecutarían siempre. Así, la instrucción if incrementa la flexibilidad al programa al ejecutar un grupo de instrucciones solamente bajo ciertas condiciones.

Problem 1
Create a program called Check; the program must open a Message Box only if the input number is less than 10 as shown.
Cree un programa llamado Check; el programa debe abrir una Caja de Mensaje solo si el número de entrada es menor a 10 como se muestra.

Check

Tip
In the previous program the input value is 5 which is less than 10 and the message box is displayed. In the figure below, the input value is 22.2, which is not less than 10 and the message box is not displayed.
En el programa previo el valor de entrada de 5 el cual es menor a 10 y la caja de mensajes es mostrada. En la figura de abajo, la entrada es 22.2 la cual no es menor a 10 y la caja de mensajes no se muestra.

CheckFalse

Tip
The sentence if is typically represented by a rhomboid in a block diagram with two outputs: YES and NO. The figure below shows a block diagram for the sentence if.
La sentencia if se representa típicamente por un rombo en un diagrama de bloques con dos salida: SI y NO. La figura de abajo muestra un diagrama de bloques para la sentencia if.

CheckBlockDiagram

Blocks of Code

It is possible to group one or more commands using curly brackets as shown in the example.
Es posible agrupar uno o más comandos usando las llaves como se muestra en el ejemplo.

BlockCode

Indentation

C, C++, C#, Javascript, and Java are languages that ignore spaces, tabs, carriage returns, empty lines, etc. However, humans have adopted a standard style called indention to ease program reading. When the indentation is used, a tab must be inserted after opening a curly bracket; and one tab level is reduced when the curly bracket is closed.
C, C++, C#, Javascript, and Java son lenguajes que ignoran los espacios, los tabuladores, los retornos de carros, líneas vacías, etc. Sin embargo, los humanos han adoptado un estilo estándar llamado indentado para facilitar la lectura del programa. Cuando la indentación es usada, un tabulador debe insertarse después de abrir una llave; y un nivel de tabulación es reducido cuando la llave se cierra.

Indentation

Problem 2
Indicate whether the next statement is true or false: The purpose of indenting is only visual because it allows easily finding where the blocks of code begin and end. However, a program may run faster when the program is indented than when it is not.
Diga si la siguiente sentencia es verdadera o falsa: El propósito del indentado es solo estético ya que permite más fácilmente ver donde comienzan y terminan los bloques de código. Sin embargo, el programa puede correr más rápido cuando el programa esta indentado que cuando no lo está.

Problem 3
Indicate whether the next statement is true or false: First, the programmer must write all code of a program, without worrying about the indenting. Once the program is properly working, the user must indent the program by adding the respective tabs.
Diga si la siguiente sentencia es verdadera o falsa: Primero, se escribe todo el código de programa, sin preocuparse por el indentado. Una vez que el programa está funcionando se hacen todas las indentaciones insertando tabs.

Problem 4
Compute the output of the following code.
Calcule la salida del código siguiente.

Program.cpp
void Programa::Window_Open(Win::Event& e)
{
     int n =15;

     if (n>5)
     {
          this->MessageBox(L"bigger than 5", L"TtC", MB_OK);
     }
     this->MessageBox(L"ooo", L"ABS", MB_OK);
}


Tip
When the instruction if has a block of code (a set on instructions surrounded by curly brackets) the instruction will affect all the instruction inside the block. On the other hand, When there is a instruction if without curly brackets, the instruction affects only the next instruction. Thus, the codes A, B, C, and D shown below are equivalent.
Cuando la instrucción if tiene un bloque de código (un conjunto de instrucciones encerradas entre llaves) la instrucción afectará a todos las instrucciones adentro del bloque. Por otro lado, cuando se tiene una instrucción if sin llaves, este afectará solamente a la siguiente instrucción. Así, los códigos A, B, C y D mostrados debajo son equivalentes.

Program.cpp
//_______________________ Code A
if (x>5)
{
     z = z+2;
}
//_______________________ Code B
if (x>5) z = z+2;
//_______________________ Code C
if (x>5)
     z = z+2;
//_______________________ Code D
if (x>5)
z = z+2;


Tip
The codes W, X, Y, and Z shown below are equivalent.
Los códigos W, X, Y y Z mostrados debajo son equivalentes.

Program.cpp
//_______________________ Code W
int x = 22;
double y = 11.1;
double z = 18.5;
if (x > 10)
{
     y = 23.0;
}
z = 25.0;
//_______________________ Code X
int x = 22;
double y = 11.1;
double z = 18.5;
if (x > 10)
     y = 23.0;
z = 25.0;
//_______________________ Code Y
int x = 22;
double y = 11.1;
double z = 18.5;
if (x > 10) y = 23.0;
z = 25.0;
//_______________________ Code Z
int x = 22;
double y = 11.1;
double z = 18.5;
if (x > 10) y = 23.0; z = 25.0;


Problem 5
Compute the output of the following code.
Calcule la salida del código siguiente.

Program.cpp
void Programa::Window_Open(Win::Event& e)
{
     int x = 0;

     if (x>1) this->MessageBox(L"ex", L"XYZ", MB_OK);
     this->MessageBox(L"ABC", L"Tequila", MB_OK);
}


Problem 6
Compute the output of the following code.
Calcule la salida del código siguiente.

Program.cpp
void Programa::Window_Open(Win::Event& e)
{
     double x = 1.0, y =2.2;
     if (x > y) this->MessageBox(L"Martin", L"Stefanny", MB_OK);
     if (x < y) this->MessageBox(L"Pedro", L"Nancy", MB_OK);
     this->MessageBox(L"abc", L"zyw", MB_OK);
}


Problem 7
Compute the output of the following code.
Calcule la salida del código siguiente.

Program.cpp
void Programa::Window_Open(Win::Event& e)
{
     const double x = 11.0;
     double y = 2.2;
     if (x == y) this->MessageBox(L"Rojo", L"Vicente", MB_OK);
     y = x;
     if (x == y) this->MessageBox(L"Gerardo", L"Green", MB_OK | MB_ICONINFORMATION);
}


Tip
Observe in the last problem that == is used together with the sentence if to ask if two value are equal.
Observe que en el problema anterior == es usado junto con la instrucción if para preguntar si dos valores son iguales.

Problem 8
Create a program called Incre. When the user presses the button: the value inside the textbox increases in 10 if the number is positive, and remains the same is the number is negative.
Cree un programa llamado Incre. Cuando el usuario presiona el botón: el valor dentro de la caja de texto se incrementa en 10 si el número es positivo, y permanece el mismo valor si es negativo.

Incre

Problem 9
javaRepeat the previous problem using Java.
javaRepita el problema previo usando Java.

IncreJRun1

IncreJRun2

IncreJ.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class IncreJ extends JFrame implements ActionListener
{
     private JTextField tbxInput;
     private JButton btCalculate;

     public IncreJ()
     {
          this.setTitle("IncreJ");
          //
          Container pane = this.getContentPane();
          pane.setLayout(new FlowLayout());
          //
          //______________________________________________ tbxInput
          tbxInput = new JTextField(10);
          pane.add(tbxInput);
          //______________________________________________ btCalculate
          btCalculate = new JButton("Calculate");
          pane.add(btCalculate);
          btCalculate.addActionListener(this);
     }

     public void actionPerformed(ActionEvent e)
     {
          if (e.getSource() == btCalculate)
          {
               final double input = Double.parseDouble(tbxInput.getText());
               if (input > 0)
               {
                    tbxInput.setText(Double.toString(input+10.0));
               }
          }
     }

     public static void main(String[] args)
     {
          IncreJ frame = new IncreJ();
          frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          frame.pack();
          frame.setVisible(true);
     }

}


Problem 10
Create a program Wintempla program called Mayor. When the user presses the button: the two input values are separated in Big and Small.
Cree un programa de Wintempla llamado Mayor. Cuando el usuario presiona el botón: los dos valores de entrada son separados en Big y Small.

Mayor One

Mayor Two

Problem 11
javaRepeat the previous problem using Java.
javaRepita el problema previo usando Java.

MayorJRun1

MayorJRun2

MayorJ.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MayorJ extends JFrame implements ActionListener
{
     private JTextField tbxInput1;
     private JTextField tbxInput2;
     private JTextField tbxBig;
     private JTextField tbxSmall;
     private JButton btSeparate;

     public MayorJ()
     {
          this.setTitle("MayorJ");
          //_____________________________________________ Left Panel
          JPanel paneLeft = new JPanel();
          paneLeft.setLayout(new GridLayout(2, 2, 5, 5)); // rows=2, cols=2, vspace=5, hspace=5
          paneLeft.add(new JLabel("Input 1"));
          tbxInput1 = new JTextField(10);
          paneLeft.add(tbxInput1);
          //
          paneLeft.add(new JLabel("Input 2"));
          tbxInput2 = new JTextField(10);
          paneLeft.add(tbxInput2);
          //_____________________________________________ Right Panel
          JPanel paneRight = new JPanel();
          paneRight.setLayout(new GridLayout(2, 2, 5, 5)); // rows=2, cols=2, vspace=5, hspace=5
          paneRight.add(new JLabel("Big"));
          tbxBig = new JTextField(10);
          paneRight.add(tbxBig);
          //
          paneRight.add(new JLabel("Small"));
          tbxSmall = new JTextField(10);
          paneRight.add(tbxSmall);
          //_____________________________________________ Main Panel
          Container pane = this.getContentPane();
          pane.setLayout(new FlowLayout());
          pane.add(paneLeft);
          //________btSeparate
          btSeparate = new JButton("Separate");
          pane.add(btSeparate);
          btSeparate.addActionListener(this);
          //
          pane.add(paneRight);
     }

     public void actionPerformed(ActionEvent e)
     {
          if (e.getSource() == btSeparate)
          {
               final double input1 = Double.parseDouble(tbxInput1.getText());
               final double input2 = Double.parseDouble(tbxInput2.getText());
               if (input1 < input2)
               {
                    tbxBig.setText(Double.toString(input2));
                    tbxSmall.setText(Double.toString(input1));
               }
               else
               {
                    tbxBig.setText(Double.toString(input1));
                    tbxSmall.setText(Double.toString(input2));
               }
          }
     }

     public static void main(String[] args)
     {
          MayorJ frame = new MayorJ();
          frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          frame.pack();
          frame.setVisible(true);
     }

}

© Copyright 2000-2021 Wintempla selo. All Rights Reserved. Jul 22 2021. Home